package com.it.gmall.payment.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.gmall.model.enums.PaymentType;
import com.it.gmall.model.order.OrderInfo;
import com.it.gmall.model.payment.PaymentInfo;
import com.it.gmall.payment.config.AlipayConfig;
import com.it.gmall.payment.mapper.OrderInfoMapper;
import com.it.gmall.payment.mapper.PaymentInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    // 创建支付客户端
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private PayService payService;

    // 点击支付宝支付之后 支付宝返回一个页面 弹出二维码
    @Override
    public String submitPay(Long orderId) {
        // 生成一张支付表 供财务系统使用 并返回这张表的信息
        PaymentInfo paymentInfo = payService.savePaymentInfo(orderId, PaymentType.ALIPAY);

        // 向支付宝请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 异步路径
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        // 回调路径
        request.setReturnUrl(AlipayConfig.return_payment_url);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", paymentInfo.getOutTradeNo()); // 交易号 唯一
        bizContent.put("total_amount", paymentInfo.getTotalAmount()); // 总金额
        bizContent.put("subject", paymentInfo.getSubject()); // 商品体描述
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); // 销售产品码 电脑网页仅支持FAST_INSTANT_TRADE_PAY
        //bizContent.put("time_expire", "2022-08-01 22:00:00"); // 绝对强制过期时间

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");

            return response.getBody();
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    // 数据库保存的实际总金额
    @Override
    public PaymentInfo getPaymentInfo(String outTradeNo) {
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>().eq("out_trade_no", outTradeNo));
        return paymentInfo;
    }

    // 退款
    @Override
    public String alipayRefund(String outTradeNo) {
        // 支付信息
        PaymentInfo paymentInfo = getPaymentInfo(outTradeNo);

        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("refund_amount", paymentInfo.getTotalAmount());

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
            if(response.isSuccess()){
                System.out.println("退款成功");
                return "success";
            } else {
                System.out.println("退款失败");
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    // 关闭交易接口
    @Override
    public String alipayTradeClose(long orderId) {
        try {
            // 根据订单id 获取交易号
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
            request.setBizContent(bizContent.toString());
            AlipayTradeCloseResponse response =  alipayClient.execute(request);
            if(response.isSuccess()){
                return "success";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "fail";
    }
}
